import { useEffect } from "react"
import "./App.css"
import type { TodoItem } from "./index"

import TodoHeader from "./components/todo-header"
import TodoList from "./components/todo-list/"
import TodoBottom from "./components/todo-bottom"
import Test from "./components/test"

import { useCallbackState } from "./Hooks/useCallbackState"

function App() {
  const [todoList, setTodoList] = useCallbackState<Array<TodoItem>>([])

  const [isAllCheckStatus, setIsAllCheckStatus] = useCallbackState<boolean>(false)

  const updateIsAllCheckStatus = (v?: Array<TodoItem>) => {
    let newVal: boolean
    if (v) {
      newVal = v.every(todo => todo.isCheck)
    } else {
      newVal = todoList.every(todo => todo.isCheck)
    }

    setIsAllCheckStatus(newVal)
  }
  useEffect(updateIsAllCheckStatus, [])

  const addTodo = (todoName: string) => {
    setTodoList([...todoList, { name: todoName, isCheck: false }], v => {
      updateIsAllCheckStatus(v)
    })
  }
  const removeTodo = (index: number) => {
    setTodoList(
      todoList.filter((todo, i: number) => i !== index),
      v => {
        updateIsAllCheckStatus(v)
      }
    )
  }
  const removeAllCheckedTodo = () => {
    setTodoList(
      todoList.filter(todo => !todo.isCheck),
      v => {
        updateIsAllCheckStatus(v)
      }
    )
  }
  const todoCheckChange = (index: number) => {
    const newVal = todoList.map((todo, i: number) => ({
      name: todo.name,
      isCheck: i === index ? !todo.isCheck : todo.isCheck,
    }))
    setTodoList(newVal, v => {
      updateIsAllCheckStatus(v)
    })
  }
  const allCheckChange = () => {
    setIsAllCheckStatus(!isAllCheckStatus, val => {
      const newTodoList = todoList.map(todo => ({
        name: todo.name,
        isCheck: val,
      }))
      setTodoList(newTodoList)
    })
  }
  return (
    <div className="App">
      <TodoHeader addTodoEvent={addTodo}></TodoHeader>
      <TodoList
        todoList={todoList}
        removeTodoEvent={removeTodo}
        todoCheckChangeEvent={todoCheckChange}
      ></TodoList>
      {todoList.length ? (
        <TodoBottom
          removeAllCheckedTodoEvent={removeAllCheckedTodo}
          isAllCheckStatus={isAllCheckStatus}
          allCheckChangeEvent={allCheckChange}
        ></TodoBottom>
      ) : (
        ""
      )}
      <Test></Test>
    </div>
  )
}

export default App
